package ms.jasim.framework;

import java.util.HashMap;
import java.util.Map;

public class JasimFramework {
	
	private static IJasimAppContext context;
	private static Map<Class<? extends IEvaluator>, IEvaluator> evaluatorMap;
	
	public static IJasimAppContext getRootContext() {
		if (context == null) 
			context = new JasimAppContext(null, "$root");
		return context;
	}

	public static IConfiguration getConfiguration() {
		return context != null ? context.getService(IConfiguration.class): null;
	}
	
	public static IDescriptorProvider getDescriptorProvider(IJasimAppContext localContext) {
		return getService(localContext, IDescriptorProvider.class);
	}
	
	public static <T> T getService(IJasimAppContext localContext, Class<T> clazz) {
		if (localContext == null)
			localContext = getRootContext();
		return localContext.getService(clazz);
	}
	
	public static IEvaluator getEvaluator(Class<? extends IEvaluator> clazz) {
		if (evaluatorMap == null)
			evaluatorMap = new HashMap<Class<? extends IEvaluator>, IEvaluator>();
		if (evaluatorMap.containsKey(clazz))
			return evaluatorMap.get(clazz);
		try {
			IEvaluator evaluator = clazz.newInstance();
			evaluatorMap.put(clazz, evaluator);
			return evaluator;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	@SuppressWarnings("unchecked")
	public static IEvaluator getEvaluator(String classID) {
		try {
			Class cls = Class.forName(classID);
			return getEvaluator(cls);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public static IEvaluator.Info getEvaluatorInfo(String classID) {
		try {
			Class<? extends IEvaluator> cls = (Class<? extends IEvaluator>) Class.forName(classID);
			return getEvaluatorInfo(cls);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static IEvaluator.Info getEvaluatorInfo(Class<? extends IEvaluator> clazz) {
		if (clazz != null)
			return clazz.getAnnotation(IEvaluator.Info.class);
		return null;
	}
}
